﻿using AutoMapper;
using Newtonsoft.Json.Serialization;
using RestApp.UI.Core;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using models = RestApp.UI.Models;

namespace RestApp.UI.Controllers
{
    public class GraphicsController : ApiController
    {
        public HttpResponseMessage Get(int idUser)
        {
            IBusinessFactory _factory = new RestApp.UI.Core.BusinessLogic();
            var graphics = _factory.WorkGraphicLogic.GetByUserId(idUser);
            var mappedEntities = Mapper.Map<IEnumerable<models.WorkGraphic>>(graphics);

            var formatter = new JsonMediaTypeFormatter();
            var json =formatter.SerializerSettings;

            json.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
            json.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
            json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            json.Formatting = Newtonsoft.Json.Formatting.Indented;
            json.ContractResolver = new CamelCasePropertyNamesContractResolver();
            json.Culture = new CultureInfo("en-US");

            var responseEntities = mappedEntities
                .OrderByDescending(t => new DateTime(t.Year.Value, t.Month.Value, t.Day.Value))
                .Select(t => new
                {
                    start = string.Format("{0}-{1}-{2}", t.Year, t.Month, t.Day),
                    title = string.Format("{0}-{1}", string.Format("{0:hh\\:mm}", t.StartTime.Value), string.Format("{0:hh\\:mm}", t.EndTime.Value)),
                    allDay = false,
                    id = t.Id,
                    year = t.Year,
                    month = t.Month,
                    day = t.Day,
                    startWorkTime = string.Format("{0:hh\\:mm}", t.StartTime.Value),
                    endWorkTime = string.Format("{0:hh\\:mm}", t.EndTime.Value)
                })
                .ToList();

            return Request.CreateResponse(HttpStatusCode.OK, responseEntities, formatter);
        }
    }
}
